package io.feige.rpc.consumer.network.handler;

import io.feige.rpc.protocol.nettyobj.pojo.Ping;

import java.net.SocketTimeoutException;
 




import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.DefaultExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 

public class StateCheckChannelHandler extends IdleStateAwareChannelHandler {
	
	private Logger logger = LoggerFactory.getLogger(StateCheckChannelHandler.class);  
  
	@Override
	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
		 if (e.getState() == IdleState.READER_IDLE) {
			logger.info("connection time out");
			handleUpstream(ctx, new DefaultExceptionEvent(e.getChannel(), new SocketTimeoutException())); 
			e.getChannel().close();
		} if(e.getState() == IdleState.WRITER_IDLE) {
			e.getChannel().write(new Ping());
		}
		super.channelIdle(ctx, e);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
		super.messageReceived(ctx, e); 
	}
}